package com.storm.component

import org.springframework.security.access.AccessDecisionVoter
import org.springframework.security.access.AccessDecisionVoter.ACCESS_DENIED
import org.springframework.security.access.AccessDecisionVoter.ACCESS_GRANTED
import org.springframework.security.access.ConfigAttribute
import org.springframework.security.core.Authentication
import org.springframework.security.web.FilterChainProxy
import org.springframework.security.web.FilterInvocation
import org.springframework.util.AntPathMatcher


class AccessDecisionVoterCustomizer<S>:AccessDecisionVoter<S> {

    override fun supports(attribute: ConfigAttribute?): Boolean {
        return true
    }

    override fun supports(clazz: Class<*>?): Boolean {
        return true
    }

    override fun vote(
        authentication: Authentication,
        s: S,
        attributes: MutableCollection<ConfigAttribute>
    ): Int {
        //可访问的数据
        val authorities = authentication.authorities
        if (s is FilterInvocation) {
            val request = s.request
            val method = request.method
            val path = request.requestURI
            val nowUrl = "${method.uppercase()} $path"
            //判断当前访问url 是否包含在权限之内
            authorities.forEach { auth->
                if (AntPathMatcher().match(auth.authority, nowUrl)) {
                    return ACCESS_GRANTED
                }
            }
        }
        return ACCESS_DENIED
    }
}